<style lang="scss" scoped>
    @import '~@/scss/public.scss';
    .bind-item{
        width: 200px;
        text-align: center;
        display: inline-block;
        cursor: pointer;
        padding-top: 10px;
        padding-bottom: 10px;
        @include hover-shadow;
        img{
            height: 30px;
            display: block;
            margin: 0 auto;
            margin-bottom: 10px;
        }
    }
    .sex-btn{
        padding: 0px 10px;
        display: inline-block;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        border:1px solid #eee;
        img{
            opacity: .3;
            height: 20px;
            margin-right: 10px;
        }
        &:hover{
            img{
                opacity:.8;
            }
        }
    }
    input[name=sex]{
        display: none;
        &:checked{
            &+img+span{
                color: #ff6c00;
            }
            &+img{
                opacity:1;
            }
        }
    }

    // 头像上传
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }

    .avatar-uploader-icon {
        font-size: 24px;
        color: #8c939d;
        width: 128px;
        height: 128px;
        line-height: 128px;
        text-align: center;
    }

    .avatar {
        width: 40px;
        height: 40px;
        display: block;
    }

</style>
<template>
    <div>

        <div class="p20">
 
            <div v-if="userInfo.user_email" @click="dialog.emailGetCode=true" class="bind-item">
                <img src="~@/icons/mail.png">
                <div class="mb10 f-color-orange">邮箱已绑定</div>
                <el-tag type="primary">{{userInfo.user_email}}</el-tag>
            </div>
            <div v-else @click="dialog.email.Edit=true" class="bind-item">
                <img src="~@/icons/mail.png">
                <div class="mb10">邮箱未绑定</div>
                <div class="f-color-grey">绑定奖励10积分</div>
            </div>

            <div v-if="userInfo.mobile" @click="dialog.mobileGetCode=true" class="bind-item">
                <img src="~@/icons/phone.png">
                <div class="mb10 f-color-orange">手机已绑定</div>
                <el-tag type="primary">{{userInfo.mobile}}</el-tag>
            </div>
            <div v-else @click="dialog.mobileEdit=true" class="bind-item">
                <img src="~@/icons/phone.png">
                <div class="mb10">手机未绑定</div>
                <div class="f-color-grey">绑定奖励10积分</div>
            </div>

            <hr>
            <el-form label-width="80px">
                <el-form-item label="头像">
                    <el-upload
                      class="avatar-uploader"
                      action="index.php?g=asset&m=asset&a=plupload"
                      :show-file-list="false"
                      v-loading.body="upload.cooling"
                      :http-request="doUpload"
                      >
                      <img v-if="form.preAvatarPreviewUrl || userInfo.avatar" :src="form.preAvatarPreviewUrl || userInfo.avatar" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="用户名">
                    {{userInfo.user_login}}
                </el-form-item>
                <el-form-item label="昵称">
                    <el-popover v-model="popover.username" ref="popover-username" placement="top" width="160" trigger="hover">
                        <el-input v-model="form.username" size="mini" class="mb10" placeholder="输入新昵称"></el-input>
                        <div class="flex row-end">
                            <el-button type="primary" size="mini" @click="userInfoEdit('user_nicename',form.username)">确定</el-button>
                        </div>
                    </el-popover>
                    <el-tag v-popover:popover-username type="primary">{{userInfo.user_nicename}}</el-tag>
                </el-form-item>
                <el-form-item label="积分">
                    {{userInfo.score}}
                </el-form-item>
                <el-form-item label="性别">
                    <label class="sex-btn" @click="userInfoEdit('sex',1)">
                        <input type="radio" name="sex" :checked="userInfo.sex==1">
                        <img src="~@/icons/sex-male.png" height="20" alt="">
                        <span>男</span>
                    </label>
                    <label class="sex-btn" @click="userInfoEdit('sex',2)">
                        <input type="radio" name="sex" :checked="userInfo.sex==2">
                        <img src="~@/icons/sex-female.png" height="20" alt="">
                        <span>女</span>
                    </label>
                </el-form-item>
                <el-form-item label="地区">
                    <el-popover v-model="popover.area" ref="popover-area" placement="top" width="160" trigger="hover">
                        <el-input v-model="form.area" size="mini" class="mb10" placeholder="输入地区名"></el-input>
                        <div class="flex row-end">
                            <el-button type="primary" size="mini" @click="userInfoEdit('area',form.area,'change_user_ext')">确定</el-button>
                        </div>
                    </el-popover>
                    <el-tag v-popover:popover-area type="primary">{{userInfo.area || '未设置'}}</el-tag>
                </el-form-item>
                <el-form-item label="QQ">
                    <el-popover v-model="popover.qq" ref="popover-qq" placement="top" width="160" trigger="hover">
                        <el-input v-model="form.qq" size="mini" class="mb10" placeholder="输入地区名"></el-input>
                        <div class="flex row-end">
                            <el-button type="primary" size="mini" @click="userInfoEdit('qq',form.qq,'change_user_ext')">确定</el-button>
                        </div>
                    </el-popover>
                    <el-tag v-popover:popover-qq type="primary">{{userInfo.qq}}</el-tag>
                </el-form-item>
                <el-form-item label="微信">
                    <el-popover v-model="popover.weixin" ref="popover-weixin" placement="top" width="160" trigger="hover">
                        <el-input v-model="form.weixin" size="mini" class="mb10" placeholder="输入地区名"></el-input>
                        <div class="flex row-end">
                            <el-button type="primary" size="mini" @click="userInfoEdit('weixin',form.weixin,'change_user_ext')">确定</el-button>
                        </div>
                    </el-popover>
                    <el-tag v-popover:popover-weixin type="primary">{{userInfo.weixin}}</el-tag>
                </el-form-item>
            </el-form>

            
        </div>

        <el-dialog title="修改手机" :visible.sync="dialog.mobileGetCode" size="tiny">
            <el-form label-width="100px" class="ui-form" :model="form" ref="dialogMobileEdit">
                <el-form-item label="当前手机">
                    <el-input v-model="userInfo.mobile" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="验证码" placeholder="输入手机收到的验证码" prop="code" :rules="{ validator: checkCode, trigger: 'blur' }">
                    <el-input v-model="form.code" style="width:135px"></el-input>
                    <el-button @click="getCodeByMobile">获取验证码</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button type="primary" @click="openBindMobile">下一步</el-button>
            </span>
        </el-dialog>
        <el-dialog title="绑定新手机" :visible.sync="dialog.mobileEdit" size="tiny">
            <el-form label-width="100px" class="ui-form">
                <el-form-item label="新手机">
                    <el-input v-model="form.newMobile" placeholder="输入新的手机号"></el-input>
                </el-form-item>
                <el-form-item label="确认新手机">
                    <el-input v-model="form.newMobileRecheck" placeholder="再次输入新手机号"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="bindMobile" type="primary" >确认修改</el-button>
            </span>
        </el-dialog>
        <el-dialog title="修改邮箱" :visible.sync="dialog.emailGetCode" size="tiny">
            <el-form label-width="100px" class="ui-form" :model="form" ref="dialogEmailEdit">
                <el-form-item label="当前邮箱">
                    <el-input v-model="userInfo.user_email" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="验证码" placeholder="输入手机收到的验证码" prop="code" :rules="{ validator: checkCode, trigger: 'blur' }">
                    <el-input v-model="form.code" style="width:135px"></el-input>
                    <el-button @click="getCodeByEmail">获取验证码</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button type="primary" @click="openBindEmail">下一步</el-button>
            </span>
        </el-dialog>
        <el-dialog title="绑定新邮箱" :visible.sync="dialog.emailEdit" size="tiny">
            <el-form label-width="100px" class="ui-form">
                <el-form-item label="新邮箱">
                    <el-input v-model="form.newEmail" placeholder="输入新的邮箱"></el-input>
                </el-form-item>
                <el-form-item label="确认新邮箱">
                    <el-input v-model="form.newEmailRecheck" placeholder="再次输入新邮箱"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="bindEmail" type="primary" >确认修改</el-button>
            </span>
        </el-dialog>
    </div>

</template>

<script>
    import lrz from 'lrz';// 图片压缩
    export default {
        data(){
            return {
                dialog:{
                    mobileGetCode:false,
                    mobileEdit:false,
                    emailGetCode:false,
                    emailEdit:false,
                },
                popover:{
                    username:false,
                    area:false,
                    qq:false,
                    weixin:false
                },
                form:{
                    code:'',
                    newMobile:'',
                    newMobileRecheck:'',
                    newEmail:'',
                    newEmailRecheck:'',
                    username:'',
                    area:'',
                    qq:'',
                    weixin:''
                },
                upload:{
                    preAvatorPreviewUrl:'',
                    cooling:false,
                },
            }
        },
        computed:{
            userInfo(){
                return this.$store.state.userInfo
            },
        },
        methods:{
            getCodeByMobile(e){
                this.$clickCooling(e.target)
                this.$http.post('index.php?g=home&m=Users&a=get_check_code',{
                    mobile: this.userInfo.mobile,
                    type: 1
                }).then(({data}) => {
                    console.log('获取手机验证码:',data);
                    this.$alert(data.msg)
                })
            },
            bindMobile(){
                if (this.form.newMobile!==this.form.newMobileRecheck) {
                    this.$alert('两次输入不一致')
                    return
                }
                this.$http.post('index.php?g=home&m=Users&a=set_mobile',{
                    code: this.code,
                    mobile: this.form.newMobile
                }).then(({data}) => {
                    console.log('关联手机:', data);
                    this.$alert(data.msg)
                    if (data.code===1) {
                        this.reloadUserInfo()
                        this.dialog.mobileEdit = false
                    }
                })
            },
            openBindMobile(){
                this.$refs['dialogMobileEdit'].validate((valid) => {
                    if (valid) {
                        // 打开绑定手机的窗口
                        this.dialog.mobileGetCode=false;
                        this.dialog.mobileEdit=true
                    } else {
                        return false;
                    }
                });
            },
            getCodeByEmail(e){
                this.$clickCooling(e.target)
                this.$http.post('index.php?g=home&m=users&a=get_email_check_code',{
                    email: this.userInfo.user_email,
                    type:1
                }).then(({data}) => {
                    console.log('邮箱验证码已发送:', data);
                    data.msg && this.$message(data.msg)
                })
            },
            bindEmail(){
                if (this.form.newEmail !== this.form.newEmailRecheck) {
                    this.$alert('两次输入不一致')
                    return
                }
                this.$http.post('index.php?g=home&m=Users&a=set_email', {
                    code: this.form.code,
                    email: this.form.newEmail
                }).then(({data}) => {
                    console.log('关联邮箱:', data)
                    this.$alert(data.msg)
                    if (data.code===1) {
                        this.reloadUserInfo()
                        this.dialog.emailEdit = false
                    }
                })
            },
            openBindEmail(){
                this.$refs['dialogEmailEdit'].validate((valid) => {
                    if (valid) {
                        // 打开绑定手机的窗口
                        this.dialog.emailGetCode=false;
                        this.dialog.emailEdit=true
                    } else {
                        return false;
                    }
                });
            },
            doUpload(config){
                console.log('上传配置',config);
                // 压缩
                lrz(config.file, {
                    width: 128
                })
                .then( (rst)=> {
                    // 处理成功会执行
                    console.log('图片已压缩：', rst);

                    let formData = new FormData()

                    formData.append('file', rst.file, config.file.name)
                    formData.append('app', 'User')

                    this.upload.cooling = true
                    // 上传到ftp
                    this.$axios({
                        method:'POST',
                        url: 'index.php?g=asset&m=asset&a=plupload',
                        data:formData,
                        headers:{'Content-Type':'multipart/form-data'},
                    }).then(({data}) => {
                        console.info('上传到ftp成功:', data);
                        this.upload.cooling = false
                        if (data.status==1) {
                            // 保存上传好的图片url
                            this.userInfoEdit('avatar', data.filepath)

                            // 生成本地预览
                            this.form.preAvatorPreviewUrl = URL.createObjectURL(config.file)
                        }
                    }).catch((e) => {
                        console.error('ftp上传失败',e);
                        this.upload.cooling = false
                    })

                }).catch( ()=> {
                    // 压缩处理失败会执行
                    this.$message.error('图片压缩失败，请换一张试试')
                })
            },
            userInfoEdit(field,value,urlParams='change_user_info'){//修改用户数据
                this.$http.post(`index.php?g=home&m=Users&a=${urlParams}`,{
                    field: field,
                    value: value
                }).then(({data})=>{
                    console.log(`修改${field}`, data);
                    if (data.code===1) {
                        this.reloadUserInfo()
                    }else{
                        this.$alert(data.msg)
                    }
                })
            },
            reloadUserInfo(){// 获取用户数据
                this.$http.get('index.php?g=home&m=Users&a=user_info')
                .then(({data})=>{
                    if (data.code===1) {
                        this.$store.commit({
                            type: 'update', //mutaitions 操作数据类型
                            data: data.data,//要保存的数据
                            modules: 'userInfo' //保存到哪个模块
                        })
                    }
                })
            },
            checkCode(rule, value, callback){//检测验证码
                if (!value) {
                    callback(new Error('验证码不能为空'))
                    return 
                }
                let style= this.dialog.mobileGetCode? 1:2
                this.$http.get('index.php?g=home&m=Users&a=check_code', {
                    params:{
                        code:this.form.code,
                        style: style,
                        type:1
                    }
                })
                .then(({data})=>{
                    // console.log('手机验证码校验',data)
                    if (data.code===1) {
                        callback();
                    }else{
                        callback(new Error(data.msg));
                    }
                })
            },
        },
    }
</script>